package com.lucas.servlet.chapter3_1.service.iml;

import com.lucas.servlet.chapter3_1.entity.User;
import com.lucas.servlet.chapter3_1.service.UserService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    private final JdbcTemplate jdbcTemplate;

    public UserServiceImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int addUser(User user) {
        String sql = "insert into users(username, password, sex) values (?,?,?)";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getSex());
    }

    @Override
    public int updateUser(User user) {
        String sql = "update users set username =?, password =?, sex =? where id =?";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getSex(), user.getId());
    }

    @Override
    public int deleteUser(int id) {
        String sql = "delete from users where id =?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public User findUser(int id) {
        String sql = "select id, username, password, sex from users where id =?";
        return jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setSex(rs.getString("sex"));
            return user;
        }, id);
    }
}